import os
import uuid
import json
from dotenv import load_dotenv
from pathlib import Path
#from pydantic import BaseSettings
from pydantic_settings import BaseSettings
import subprocess
import tempfile

PROMPT_CFG = Path(__file__).resolve().parent.parent / "prompt_config.json"

load_dotenv()

class Settings(BaseSettings):
    # 视觉模型
    visual_base_url: str
    visual_model_id: str
    visual_token: str
    # 合规模型
    compliance_base_url: str
    compliance_model_id: str
    compliance_token: str
    # SMTP
    smtp_host: str
    smtp_port: int
    smtp_user: str
    smtp_pass: str
    smtp_sender: str
    # 合规提示词
    compliance_prompt: str
    # 上传设置
    max_file_size: int
    allowed_extensions: str

    class Config:
        env_file = '.env'

settings = Settings()


def save_upload_file(upload_file, upload_dir: Path) -> Path:
    upload_dir.mkdir(parents=True, exist_ok=True)
    ext = upload_file.filename.split('.')[-1]
    unique_name = f"{uuid.uuid4().hex}.{ext}"
    file_path = upload_dir / unique_name
    with open(file_path, 'wb') as f:
        f.write(upload_file.file.read())
    return file_path


def allowed_file(filename: str) -> bool:
    ext = filename.rsplit('.', 1)[-1].lower()
    return ext in settings.allowed_extensions.split(',')



def load_prompt_list() -> list[dict]:
    """
    返回一个列表，列表中每项是 { key, name, prompt }
    """
    if PROMPT_CFG.exists():
        return json.loads(PROMPT_CFG.read_text(encoding='utf-8'))
    return []

def get_prompt_by_key(key: str) -> str:
    """
    根据 key 查找对应的 prompt，否则返回一个默认提示词
    """
    for item in load_prompt_list():
        if item.get("key") == key:
            return item.get("prompt", "")
    # fallback 到 .env 中的 COMPLIANCE_PROMPT
    from backend.utils import settings
    return settings.compliance_prompt

